<?php

namespace addons\shopro\controller\user;

use app\admin\model\shopro\activity\GiftLog;
use app\common\library\Sms;
use addons\shopro\controller\Common;
use addons\shopro\service\user\UserAuth;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;
use app\admin\model\shopro\order\Order as OrderModel;
use app\admin\model\shopro\order\Aftersale as AftersaleModel;
use app\admin\model\shopro\ThirdOauth;
use think\Db;
use app\admin\model\activity\Eventinvite;
use app\admin\model\activityone\EventInviteLogs;
use addons\shopro\library\activity\traits\GiveGift;

class User extends Common
{
    use GiveGift;
    protected $noNeedLogin = ['smsRegister', 'accountLogin', 'smsLogin', 'resetPassword'];
    protected $noNeedRight = ['*'];


    public function _initialize()
    {
        parent::_initialize();
        \think\Lang::load(APP_PATH . 'api/lang/zh-cn/user.php');        // 加载语言包
    }

    /**
     * 用户数据
     */
    public function data()
    {
        $user = auth_user();
        // 查询用户优惠券数量
        $data['coupons_num'] = UserCouponModel::geted()->where('user_id', $user->id)->count();

        // 订单数量
        $orderNum = [];
        $orderNum['unpaid'] = OrderModel::where('user_id', $user->id)->unpaid()->count();
        $orderNum['nosend'] = OrderModel::where('user_id', $user->id)->pretendPaid()->nosend()->count();
        $orderNum['noget'] = OrderModel::where('user_id', $user->id)->pretendPaid()->noget()->count();
        $orderNum['nocomment'] = OrderModel::where('user_id', $user->id)->paid()->nocomment()->count();
        $orderNum['aftersale'] = AftersaleModel::where('user_id', $user->id)->needOper()->count();

        $data['order_num'] = $orderNum;

        $this->success('用户数据', $data);
    }

    /**
     * 第三方授权信息
     */
    public function thirdOauth()
    {
        $user = auth_user();

        $provider = $this->request->param('provider', '');
        $platform = $this->request->param('platform', '');
        if (!in_array($platform, ['miniProgram', 'officialAccount', 'openPlatform'])) {
            $this->error(__('Invalid parameters'));
        }
        $where = [
            'platform' => $platform,
            'user_id' => $user->id
        ];
        if ($provider !== '') {
            $where['provider'] = $provider;
        }
        $oauth = ThirdOauth::where($where)->field('nickname, avatar, platform, provider')->find();
        $this->success('', $oauth);
    }

     /**
     * 跑步活动列表
     */
    public function runninglist(){
        $runninglist = Db::name('event_checkin')->order('id desc')->select();
        $this->success('获取成功',$runninglist); 
    }
     /**
     * 拉新活动列表
     */

     public function laxinlist(){
        $laxin = Db::name('event_invite')->order('id desc')->select();
        $this->success('获取成功',$laxin); 
     }
         // 获取已拉新的用户
         public function sharedetail()
         {
            $user = auth_user(true);
            $user_id =$user->id;
           
            $eventid = input('param.eventid');
            $shareuserid = input('param.shareuserid');
            $query = "select f1.nickname,date_format(f.created_at, '%Y-%m-%d') as created_at,CONCAT('https://www.paopaomala.top/',f1.avatar) as avatar  from fa_event_invite_logs f 
            inner join fa_user f1 on  f.user_id=f1.id
             where f.status=1 and share_user_id=:userid and event_invite_id=:eventid;";
            $sharelist = Db::query($query, ['userid' =>$user_id,'eventid'=>$eventid]);
    
            $where = [
                'id' => $eventid
            ];
            $laxin = Db::name('event_invite')->where($where)->find();
            $userInfo = Db::name('user')->where('id',$user_id)->find();
            if($userInfo['level'] > 0){
                $isMember = true;
            }else{
                $isMember = false;
            }
    
            $query = "select TIMESTAMPDIFF(DAY, NOW(),DATE_ADD(FROM_UNIXTIME(upgradetime), 
            INTERVAL (select limit_days from fa_event_invite f  where id=:eventid) DAY))
            days from fa_user where id=:userid;";
    
            $diffdays= Db::query($query, ['userid' =>$user_id,'eventid'=>$eventid]);

            $exites = EventInviteLogs::where([
                'user_id'  => $user_id,
                'status'  => 1,
                'event_invite_id'  => $eventid,
            ])->count();
            
            $curNickName='';
            $curAvatar='';
            $currUserId =$user_id;
            if($shareuserid)
            {
                $currUserId  =$shareuserid;
           

            }
            $curUserInfo= Db::name('user')->where('id='.$currUserId)->find();
            $curNickName= $curUserInfo['nickname'];
            $curAvatar ='https://www.paopaomala.top'.$curUserInfo['avatar'];
            $cityTxt=[];
            if($laxin['city'])
            {
                $citys =  explode(",",$laxin['city']);
                foreach($citys as $city)
                {
                    $area = Db::name('area')->where(['id'=>$city])->field('name')->find();
                    $cityTxt[]= $area['name'];
                }
            }         
            $data= [
                'detail' => $laxin,
                'sharelist' => $sharelist,
                'isMember' =>$isMember,
                'curuserid'=>$userInfo['id'],
                'diffdays'=>$diffdays[0]['days'],
                'exites'=>$exites,
                'curNickName'=>$curNickName,
                'curAvatar'=>$curAvatar,
                'cityTxt'=>$cityTxt

            ];
            $this->success('success',$data);
    
         }

     
         public function updateinvitelog()
         {
            $user = auth_user(true);
            $userid = $user->id;
            $eventid =  input('param.eventid');  

            $exites = EventInviteLogs::where([
                'user_id'  => $userid,
                'event_invite_id'  => $eventid,
            ])->whereIn('status', [1, 2])->count();
            
            //判断是否已经邀请过
            if ($exites){
               $this->success('已经参与过活动','已经参与过活动',-1);
            }
         
    
            $eventinfo = Eventinvite::where('id','=',$eventid)->find();
            $eventinfo->gift = $eventinfo->gift_coupon;   //重置gift 属性
            
            // $limitdays = date('Y-m-d', strtotime("-{$eventinfo['limit_days']} days"));    

           
            $eventinvitelogModel=  Db::name('event_invite_logs')->where([
                'user_id'=>$userid,
                'event_invite_id'=>$eventid,
            ])->find();
            if($eventinvitelogModel ==null)
            {
                $this->success('您已参加过此类活动','您已参加过此类活动',-1);
            }
            $share_user_id = $eventinvitelogModel['share_user_id'];
            if($share_user_id == $userid)
            {
              $this->success('不能给自己点赞','不能给自己点赞',-1);
            }
            
            $query = "select TIMESTAMPDIFF(DAY, NOW(),DATE_ADD(FROM_UNIXTIME(upgradetime), 
            INTERVAL (select limit_days from fa_event_invite f  where id=:eventid) DAY))
            days from fa_user where id=:userid;";
            $inviteModel =  Db::name('event_invite')->where(['id'=>$eventid])->find();
            if($inviteModel['is_repeat']==2)
                {
                    $diffdays= Db::query($query, ['userid' =>$share_user_id,'eventid'=>$eventid]);
                    if(intval($diffdays[0]['days']) <0)
                    {
                        $this->success('活动已到期','活动已到期',-1);
                    }
                }
          
          
            /**
             * 获取用户拉新数量(会员才算 user.level >  0)
             */
          

            $where = [
                'share_user_id'=>$share_user_id,
                'event_invite_id'=>$eventid,
                'status'=>1
            ];
            // if($inviteModel['is_repeat']==2)
            // {
            //     $where[] = ['created_at','>',$limitdays];
            // }
            $laxincount = EventInviteLogs::where([
                    'share_user_id'=>$share_user_id,
                    'event_invite_id'=>$eventid,
                    'fa_event_invite_logs.status'=>1
                ])
                ->where('user.level','>',0)
                ->join('user','fa_user.id=fa_event_invite_logs.user_id')
                ->count();
                if($laxincount >= $eventinfo['user_count_threshold'])
                {
                    $this->success('活动人数已满','活动人数已满',-1);
                }
                Db::execute('update fa_event_invite_logs set status=1 where user_id=:userid and event_invite_id=:eventid;',
                ['userid' =>$userid,'eventid'=>$eventid]);

                $laxincount = EventInviteLogs::where([
                    'share_user_id'=>$share_user_id,
                    'event_invite_id'=>$eventid,
                    'fa_event_invite_logs.status'=>1
                ])
                ->where('user.level','>',0)
                ->join('user','fa_user.id=fa_event_invite_logs.user_id')
                ->count();
            //如果拉新用户满足条件就赠送优惠券
            if ($laxincount == $eventinfo['user_count_threshold']){
                //获取发放会员信息
                $user = \app\admin\model\User::where('id','=',$share_user_id)->find();
                $this->giveCoupons($user,$eventinfo->gift_coupon);
                //查询上级
                $parent = EventInviteLogs::where([
                    'event_invite_id'=>$eventid,
                    'user_id' => $share_user_id
                ])->order('created_at','asc')->find();    
                //给上级发送券
                if ($parent){
                    $parentuser = \app\admin\model\User::where('id',$parent['share_user_id'])->find();
                    $this->giveCoupons($parentuser,$eventinfo->superior_gift_coupon);
                }
                if($inviteModel['is_repeat']==1)
                {
                    Db::execute('update fa_event_invite_logs set status=2 where  share_user_id=:share_user_id and event_invite_id=:event_invite_id;',
                                ['share_user_id'=>$share_user_id,'event_invite_id'=>$inviteModel['id']]);
                }
            }   
    
            $this->success('点赞成功','点赞成功',0);    
         }
    
    
         public function addinvitelog(){
    
                $user = auth_user(true);
                $userid = $user->id;
                $share_user_id = input('param.shareuserid');  
                if($userid == intval($share_user_id))
                {
                    $this->success('不能给自己点赞');
                    // $this->success($userid.'|'.$share_user_id,$userid.'|'.$share_user_id,-1);
                }
                $eventid =  input('param.shareeventid');  
                $eventinfo = Eventinvite::where('id','=',$eventid)->find();
                $eventinfo->gift = $eventinfo->gift_coupon;   //重置gift 属性
                $limitdays = date('Y-m-d', strtotime("-{$eventinfo['limit_days']} days"));
                 $exites = EventInviteLogs::where([
                     'user_id'  => $userid,
                    //  'share_user_id'  => $share_user_id,
                    // 'event_invite_id'  => $eventid,
                 ])->count();
                 //判断是否已经邀请过
                 if ($exites){
                    $this->success('已经参与过活动');
                    // $this->error('已经参与过活动');
                 }
    
                $Createdata = [
                    'user_id'  => $userid,
                    'share_user_id'  => $share_user_id,
                    'event_invite_id'  => $eventid,
                    'created_at'  => date("Y-m-d H:i:s"),
                    'update_at'  => date("Y-m-d H:i:s"),
                ];
                $logs = EventInviteLogs::create($Createdata);
    
                // /**
                //  * 获取用户拉新数量(会员才算 user.level >  0)
                //  */
                // $laxincount = EventInviteLogs::where('created_at','>=',$limitdays)
                //     ->where([
                //         'share_user_id'=>$share_user_id,
                //         'event_invite_id'=>$eventid,
                //     ])
                //     ->where('user.level','>',0)
                //     ->join('user','fa_user.id=fa_event_invite_logs.user_id')
                //     ->count();
                // //如果拉新用户满足条件就赠送优惠券
                // if ($laxincount == $eventinfo['user_count_threshold']){
                //     //获取发放会员信息
                //     $user = \app\admin\model\User::where('id','=',$share_user_id)->find();
                //     $this->giveCoupons($user,$eventinfo->gift_coupon);
                //     //查询上级
                //     $parent = EventInviteLogs::where([
                //         'event_invite_id'=>$eventid,
                //         'user_id' => $share_user_id
                //     ])->order('created_at','asc')->find();
    
                    
    
                //     //给上级发送券
                //     if ($parent){
                //         $parentuser = \app\admin\model\User::where('id',$parent['share_user_id'])->find();
                     
    
                //         $this->giveCoupons($parentuser,$eventinfo->gift_coupon);
                //         // echo "<pre>";
                //         // print_r($this->giveCoupons($parentuser,$eventinfo->gift_coupon));
                      
                //         // die;
                //     }
                // }
    
                $this->success('请求成功',$logs);
          
        }
    
    /**
   *  * 获取队伍列表
     */
    public function teamslist(){
        $id = input('param.id');
        $user = auth_user();
        $where = [
            'guess_id' => $id,
            'user_id' => $user->id
        ];
        $teamList = Db::name('event_guess_teams')->where('guess_id',$id)->select();
        foreach($teamList  as $k => $v)
        {
            $newteamList['data'][]=$v;
        }
        
        $guess_user = Db::name('event_guess_user')->where($where)->find();
        if($guess_user)
        {

            $newteamList['teamids']=$guess_user['team_id'];
        }

        $guessModel = Db::name('events_guess')->where('id',$id)->find();
        $endTime = $guessModel['end_time'];
        $timestamp = strtotime($endTime);
        $currentTimestamp = time();
        $isExpire = false;
        if ($currentTimestamp > $timestamp) {
            $isExpire=true;
        }
        $guessModel['isExpire']=$isExpire;
        $newteamList['guessModel']=$guessModel;
        $this->success('获取成功',$newteamList); 
    }

       /*
     * 竞猜活动接口
     */
    public function eventsguess(){
        $eventlist = Db::name('events_guess')->order('id desc')->select();
        $this->success('获取成功',$eventlist); 
    }
   
    public function eventsguessuser(){
        //用户id
       $res['user_id'] = input('param.userid');
       //活动id
       $res['event_id'] = input('param.eventid');
       //参与时间
       $res['participation_time'] = date("Y-m-d H:i:s");
       //选择的参加的队伍
       $res['team_id'] = input('param.teamid');
       $usernumb = Db::name('user')->where('id ='.$res['user_id'])->find();
       $row['numb'] = $usernumb['numb'] - 1;
       $userlistnumb = Db::name('user')->where('id ='.$res['user_id'])->update($row);
       //参加的活动id
       $res['guess_id'] = input('param.guessid');
       $result = Db::name('event_guess_user')->insert($res);
       if($result){
         $this->success('选择成功',$result); 
       }else{
         $this->error('选择失败');
       }
    }

    /**
     * 查询用户选择的详情
     */
    public function userdetail(){
        $res['user_id'] = input('param.userid');
        $res['event_id'] = input('param.eventid');
        $result = Db::name('event_guess_user')->where($res)->find();
        // if($result){
        //     $this->success('选择成功',$result); 
        //   }else{
        //     $this->error('选择失败');
        //   }
    }



    /**
     * 用户信息
     */
    public function profile()
    {
        //TODO @ldh: 1.账号被禁用 2.连表查group
        $user = auth_user(true);

        $user = UserModel::with(['parent_user', 'third_oauth'])->where('id', $user->id)->find();

        $user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);
        
        $userlevel=  Db::name('user_level')->where('level','=',$user['level'])->find();
        if($userlevel)
        {
            $user['levelTxt'] =$userlevel['level_name'];
        }

        $this->success('个人详情', $user);
    }

    /**
     * 更新用户资料
     */
    public function update()
    {
        $user = auth_user();

        $params = $this->request->only(['avatar', 'nickname', 'gender','username']);
       // print_r($params);die;

        $this->svalidate($params);

        $user->save($params);
        $user->hidden(['password', 'salt', 'createtime', 'updatetime', 'deletetime', 'remember_token', 'login_fail', 'login_ip', 'login_time']);

        $this->success('更新成功', $user);
    }

    public function updateusercity()
    {
        $user = auth_user();
        $city= input('param.city');
        Db::name('user')->where(['id'=>$user->id])->update(['city'=> $city]);
        $this->success('更新成功', $user);
    }
    /**
     * 账号密码登录
     */
    public function accountLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }

        $params = $this->request->only(['account', 'password']);
        $this->svalidate($params, '.accountLogin');

        $ret = $this->auth->login($params['account'], $params['password']);
        if ($ret) {
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError() ?: '注册失败');
        }
    }

    /**
     * 短信验证码登陆
     */
    public function smsLogin()
    {
        $user = auth_user();

        if ($user) {
            $this->error('您已登录,不需要重新登录');
        }

        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.smsLogin');
        if (!Sms::check($params['mobile'], $params['code'], 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = UserModel::getByMobile($params['mobile']);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        }else {
            $this->error('该手机号暂未注册');
        }
        if (isset($ret) && $ret) {
            Sms::flush($params['mobile'], 'mobilelogin');
            set_token_in_header($this->auth->getToken());
            $this->success(__('Logged in successful'));
        } else {
            $this->error($this->auth->getError() ?: '登录失败');
        }
    }

    /**
     * 短信验证码注册
     */
    // public function smsRegister()
    // {
    //     $user = auth_user();
    //     if ($user) {
    //         $this->error('您已登录,请先退出登录');
    //     }

    //     $params = $this->request->only(['mobile', 'code', 'password']);
    //     $parentUserId = (int)$this->request->param("parent_id");
    //     $this->svalidate($params, '.smsRegister');

    //     $ret = Sms::check($params['mobile'], $params['code'], 'register');
    //     if (!$ret) {
    //         $this->error(__('Captcha is incorrect'));
    //     }
    //     $params['parent_user_id'] = $parentUserId;
    //     // 注册
    //     $userAuth = new UserAuth();
    //     $auth = $userAuth->register($params);
    //     set_token_in_header($auth->getToken());

    //     $this->success(__('Sign up successful'));
    // }

    public function smsRegister()
    {
        $user = auth_user();
        if ($user) {
            $this->error('您已登录,请先退出登录');
        }

        $params = $this->request->only(['mobile', 'password']);
        $parentUserId = (int)$this->request->param("parent_id");
        $this->svalidate($params, 'smsRegister');

        // $ret = Sms::check($params['mobile'], 'register');
        // if (!$ret) {
        //     $this->error(__('Captcha is incorrect'));
        // }
        $params['parent_user_id'] = $parentUserId;
        // 注册
        $userAuth = new UserAuth();
        $auth = $userAuth->register($params);
        set_token_in_header($auth->getToken());
        $this->success(__('Sign up successful'));
    }

    /**
     * 修改密码
     */
    public function changePassword()
    {
        $user = auth_user();

        $params = $this->request->only(['oldPassword', 'newPassword']);
        $this->svalidate($params, '.changePassword');

        $userAuth = new UserAuth();
        $userAuth->changePassword($params['newPassword'], $params['oldPassword']);

        $this->auth->direct($user->id);
        set_token_in_header($this->auth->getToken());

        $this->success(__('Change password successful'));
    }

    /**
     * 重置/忘记密码
     */
    // public function resetPassword()
    // {
    //     $params = $this->request->only(['mobile', 'code', 'password']);
    //     $this->svalidate($params, '.resetPassword');

    //     $ret = Sms::check($params['mobile'], $params['code'], 'resetpwd');
    //     if (!$ret) {
    //         $this->error(__('Captcha is incorrect'));
    //     }

    //     $userAuth = new UserAuth();
    //     $userAuth->resetPassword($params);

    //     $this->success(__('Reset password successful'));
    // }

    public function resetPassword()
    {
        $params = $this->request->only(['mobile','password']);
        $this->svalidate($params, 'resetPassword');

        // $ret = Sms::check($params['mobile'],'resetpwd');
        // if (!$ret) {
        //     $this->error(__('Captcha is incorrect'));
        // }

        $userAuth = new UserAuth();
        $userAuth->resetPassword($params);

        $this->success(__('Reset password successful'));
    }

    /**
     * 更换手机号
     */
    public function changeMobile()
    {
        $params = $this->request->only(['mobile', 'code']);
        $this->svalidate($params, '.changeMobile');

        $ret = Sms::check($params['mobile'], $params['code'], 'changemobile');
        if (!$ret) {
            $this->error(__('Captcha is incorrect'));
        }

        $userAuth = new UserAuth();
        $userAuth->changeMobile($params);

        $this->success('绑定成功');
    }

    /**
     * 修改用户名
     */
    public function changeUsername()
    {
        $user = auth_user(true);

        $params = $this->request->only(['username']);
        $this->svalidate($params, '.changeUsername');

        $userAuth = new UserAuth();
        $userAuth->changeUsername($params);

        $this->success('绑定成功');
    }

    /**
     * 更新小程序头像和昵称
     */
    public function updateMpUserInfo()
    {
        $user = auth_user(true);

        $params = $this->request->only(['avatar', 'nickname']);
        $this->svalidate($params, '.updateMpUserInfo');

        $user->save($params);

        $thirdOauth = \app\admin\model\shopro\ThirdOauth::where('user_id', $user->id)->where([
            'provider' => 'wechat',
            'platform' => 'miniProgram'
        ])->find();
        $thirdOauth->save($params);
        $this->success('绑定成功');
    }

    //用户等级
    public function userLevel()
    {
        $user = auth_user(true);
        $user_id =  $user->id;
          $query = "select *, if(level>
          (select level from fa_user where id=:id),true,false) as isshow
           from fa_user_level f order by level;";

         $userList = Db::query($query, ['id' =>$user_id]);
         $this->success('用户数据', $userList);

    }
    public function userLevelDetail()
    {
        $user = auth_user(true);
        $user_id =  $user->id;
      
        $levelid = input('param.levelid');
           $level = Db::name('user_level')
            ->where('id',$levelid)->find();

         $this->success('用户数据', $level);

    }

    public function clickcheckin()
    {
        $row['checkin_id'] = input('param.checkinid');
        $user = auth_user(true);
        $row['user_id'] =$user->id;
        $map['is_submit'] = 1; 
        $map['is_coupon'] = 2; 
        $res = Db::name('event_checkin_user')->where($row)->update($map);
        if($res){
            $this->success('success',$res); 
        }

    }

   public function checkindetail()
   {
        $checkin_id = input('param.checkinid');
        $checkinModel= Db::name('event_checkin')->where(['id'=>$checkin_id])->find();
        $this->success('success',$checkinModel);
   }

    public function checkin()
    {   
        $checkin_id = input('param.checkinid');
        $user = auth_user(true);
        $user_id =$user->id;
        $query = "SELECT is_submit,is_coupon, DATE_FORMAT(date, '%m') AS month
        FROM fa_event_checkin_user
        WHERE user_id = :id and checkin_id = :checkin_id ;";
        $checkinList = Db::query($query, ['id' =>$user_id,'checkin_id'=>$checkin_id]);

        $checkinModel= Db::name('event_checkin')->where(['id'=>$checkin_id])->find();

        $startYear = date('Y', strtotime($checkinModel['start_time']));
        $endYear = date('Y', strtotime($checkinModel['end_time']));
        $startMonth = date('n', strtotime($checkinModel['start_time']));
        $endMonth = date('n', strtotime($checkinModel['end_time']));

        $adjustedEndMonth =$endMonth + ($endYear -$startYear) * 12;
        $newendMonth =$adjustedEndMonth ;
        $months = range(intval($startMonth), intval($newendMonth));
        $currentMonth = date('n');
        $selectedNumber = 0;
        $data =[];
        $result = [];
        $is_submit = 0;
        $is_coupon = 0;
        foreach ($months as$month) {
            $result[$month] = false; 

            foreach ($checkinList as$entry) {
                if ($entry['month'] =='0'.$month) {
                    $result[$month] = true; 
                    $is_submit = $entry['is_submit']; 
                    $is_coupon = $entry['is_coupon']; 
                    $selectedNumber= $selectedNumber+1;
                    break; 
                }
            }

        }
        $current= $result[$currentMonth] ;

    $data = [];

    foreach ($result as$month => $selected) {
        if ($month <= 12) {
            $year = '2024';
        } elseif ($month <= 24) {
            $year = '2025';
        } else {
            $year = '2026';
        }
        $formattedMonth =$month;
        if($formattedMonth>12 && $formattedMonth<=24)
        {
            $formattedMonth=$formattedMonth-12;
        }
        if($formattedMonth>24 && $formattedMonth<=36)
        {
            $formattedMonth=$formattedMonth-24;
        }
        $formattedMonth =$formattedMonth < 10 ? '0'.$formattedMonth :$formattedMonth;


        $data[] = [
            'month' => $year.'.' . $formattedMonth,
            'selected' => $selected,
            'selectedNumber'=>$selectedNumber,
            'minCount'=>$checkinModel['minCount'],
            'is_submit'=>intval($is_submit),
            'is_coupon'=>intval($is_coupon),
            'currentSelected'=>$current
            
        ];
    }

    // foreach ($result as$month => $selected) {
    //     $data[] = [
    //         'month' => $month,
    //         'selected' => $selected
    //     ];
    // }


    $this->success('success',$data);
    }
    

    public function activity()
    {
        $user = auth_user();
        $userid = $user->id;

        $activitylist = Db::name('events')->order('id desc')->select();
        $eventlist = array();
        foreach ($activitylist as $k => $v) {
            $v['duiwu'] = Db::name('event_teams')->where('event_id =' . $v['id'])
                ->order('id desc')->select();

            $v['user_select'] =   Db::name('event_user')->where('user_id', $userid)->where('event_id', $v['id'])->find();
            array_push($eventlist, $v);
        }

        $this->success('请求成功', $eventlist);
    }
    /**
     * 登出
     */
    public function logout()
    {
        $userAuth = new UserAuth();
        $userAuth->logout();

        $this->success(__('Logout successful'));
    }


    /**
     * 用户注销
     */
    public function logoff()
    {
        $userAuth = new UserAuth();
        $userAuth->logoff();

        $this->success('注销成功');
    }
    /**
     * 
     * 竞猜活动列表接口
     */
    // public function eventsguess(){
    //     $eventlist = Db::name('events_guess')->order('id desc')->select();
    //     $this->success('获取成功',$eventlist); 
    // }


}
